<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      title="编辑关联"
      @ok="handleSubmit"
      :closeFunc="handleClose"
    >
      <BasicForm @register="registerEditForm">
        <template #jsonSlot="{ model, field }">
          <CodeEditor v-model:value="model[field]" />
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { CodeEditor } from '/@/components/CodeEditor';
  import { defineEmits, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { editAssociationSchemas } from './editModal.data';
  import { modalStyleSetting } from '/@/settings/thingsBoardDesign';
  const emit = defineEmits(['success', 'register']);
  const entityId = ref<string>('');
  const editRecord = ref<any>();
  const optionValue = ref<string>('');
  const [registerEditForm, { validate, setFieldsValue, resetFields }] = useForm({
    layout: 'vertical',
    labelWidth: 200,
    schemas: editAssociationSchemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(
    async ({ record, id, optionsValue }) => {
      setModalProps({ loading: true, confirmLoading: true, ...modalStyleSetting });
      entityId.value = id;
      editRecord.value = { ...record };
      optionValue.value = optionsValue;
      setFieldsValue({
        jsonValue: record.jsonValue ? JSON.stringify(record.jsonValue) : '',
      });
      setModalProps({ loading: false, confirmLoading: false });
    },
  );

  const handleClose = async () => {
    resetFields();
    return true;
  };

  const handleSubmit = async () => {
    setModalProps({ confirmLoading: true });
    try {
      const values = await validate();
      closeModal();
      emit('success', {
        key: 'edit',
        values: {
          ...values,
          entityId: entityId.value,
          record: { ...editRecord.value },
          optionsValue: optionValue.value,
        },
      });
      resetFields();
    } catch (error) {}
    setModalProps({ confirmLoading: false });
  };
</script>
